import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:schedule_self_client/state_management/providers/login_status.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ApiCommon {
  static String baseUrl = 'https://scheduleself.smallwang.ltd:8080';

  static InterceptorsWrapper getInterceptorsWrapper(BuildContext buildContext) {
    return InterceptorsWrapper(
      onRequest:
          (RequestOptions options, RequestInterceptorHandler handler) async {
        final prefs = await SharedPreferences.getInstance();
        String? saToken = prefs.getString('user_token');
        if (saToken != null) {
          options.headers['satoken'] = saToken;
        }
        return handler.next(options);
      },
      onResponse: (Response response, ResponseInterceptorHandler handler) {
        if (response.data['success'] == true) {
          handler.next(response);
        } else {
          if ('String' == response.data['errMessage'].runtimeType.toString()) {
            BotToast.showText(text: response.data['errMessage']);
          } else {
            BotToast.showText(text: '未知异常');
          }
        }
      },
      onError: (DioException error, ErrorInterceptorHandler handler) async {
        if (error.response?.statusCode == 401) {
          BotToast.showText(text: '登录状态失效，请重新登录');
          await Provider.of<LoginInfo>(buildContext, listen: false)
              .cleanOldCache();
          return;
        }
        return handler.next(error);
      },
    );
  }
}
